package com.intel.surface;

import com.intel.bluetooth.DeviceConnectService;
import lombok.Data;

import javax.bluetooth.RemoteDevice;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;

@Data
public class UnconnectDevicePn extends JPanel {

    private static final long serialVersionUID = 1L;

    private JLabel connect;

    private RemoteDevice remoteDevice;
    private DeviceListFrame frame;

    public UnconnectDevicePn(DeviceListFrame frame, RemoteDevice remoteDevice) {
        this.frame = frame;
        this.remoteDevice = remoteDevice;

        this.setPreferredSize(new Dimension(0, 50));
        this.setLayout(new BorderLayout(0, 0));
        this.setBackground(new Color(255, 255, 255));

        JPanel left = new JPanel(new VFlowLayout());
        left.setBackground(new Color(255, 255, 255));
        {
            JLabel name = null;
            try {
                name = new JLabel(remoteDevice.getFriendlyName(false));
            } catch (IOException e) {
                e.printStackTrace();
            }
            name.setFont(new Font("黑体", Font.BOLD, 15));
            JLabel address = new JLabel(remoteDevice.getBluetoothAddress());
            address.setForeground(Color.GRAY);
            address.setFont(new Font("黑体", Font.PLAIN, 13));
            left.add(name);
            left.add(address);
        }
        this.add(left, BorderLayout.CENTER);

        JPanel right = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 12));
        right.setBackground(new Color(255, 255, 255));
        {
            connect = new JLabel();
            connect.setIcon(new ImageIcon("img/unconnect.png"));
            connect.setToolTipText("连接");
            connect.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            connect.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    super.mouseClicked(e);
                    DeviceConnectService deviceConnectService = new DeviceConnectService(UnconnectDevicePn.this);
                    deviceConnectService.connect();
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            connect.setIcon(new ImageIcon("img/wait_connect.gif"));
                            connect.updateUI();
                        }
                    });
                }

            });
            right.add(connect);
        }
        this.add(right, BorderLayout.EAST);
    }

    public void connectFail() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                connect.setIcon(new ImageIcon("img/unconnect.png"));
                connect.updateUI();
            }
        });
    }
}
